package com.amphiprion.prototype;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.view.View;

import com.amphiprion.prototype.control.ControlerState;

public class GameView extends View {
	public volatile boolean drawing;
	private List<GameScreen> screens = new ArrayList<GameScreen>();
	private int startScreen = -1;
	private ScreenProperty screenProperty = new ScreenProperty();

	public GameView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public void onInput(ControlerState state, long delay) {
		// only the last screen receive input
		if (screens.size() > 0) {
			screens.get(screens.size() - 1).onInput(state, delay);
		}
	}

	@Override
	protected void onDraw(Canvas canvas) {
		drawing = true;
		super.onDraw(canvas);
		for (int i = startScreen; i < screens.size(); i++) {
			if (i >= 0) {
				GameScreen scr = screens.get(i);
				scr.onDraw(canvas);
				screenProperty = scr.getScreenProperty();
			}
		}
		drawing = false;
	}

	public void addScreen(GameScreen screen) {
		screen.setView(this);
		screens.add(screen);
		computeStartScreen();
	}

	public void removeScreen(int number) {
		for (int i = 0; i < number; i++) {
			GameScreen scr = screens.remove(screens.size() - 1);
			scr.desactivate();
		}
		computeStartScreen();
	}

	private void computeStartScreen() {
		int newStart = screens.size() - 1;
		for (int i = screens.size() - 1; i >= 0; i--) {
			newStart = i;
			if (!screens.get(i).isLayered()) {
				break;
			}
		}
		for (int i = startScreen; i < newStart; i++) {
			if (i >= 0) {
				screens.get(i).desactivate();
			}
		}
		screens.get(newStart).activate();
		startScreen = newStart;
	}

	public ScreenProperty getScreenProperty() {
		return screenProperty;
	}

	public boolean onBackRequested() {
		if (screens.size() > 0) {
			return screens.get(screens.size() - 1).onBackRequested();
		}

		return false;
	}

	@Override
	public boolean postDelayed(Runnable action, long delayMillis) {
		throw new UnsupportedOperationException("use gameScreen.postDelayed instead");
	}
}
